package com.persistencia.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.util.List;



import com.exceptions.PersistenceException;

public class RecordBytesFile extends RecordStrategy {

	public RecordBytesFile(Class<?> classType) throws PersistenceException {
		super(classType);
		try {
			FILE_NAME += getClassTypeName() + ".obj";
			createFile();
		} catch (Exception e) {
			throw new PersistenceException(e);
		}
	}

	@Override
	public synchronized Boolean writeData(List<?> obj)
			throws PersistenceException {
		try {

			ByteArrayOutputStream bs = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bs);
			oos.writeObject(obj);
			byte[] bytes = bs.toByteArray();
			oos.close();

			// bytes to io.File
			File file = new File(FILE_NAME);
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(bytes);
			fos.flush();
			fos.close();

		} catch (Exception e) {
			throw new PersistenceException(e);
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public synchronized List<?> readData() throws PersistenceException {
		Object theQueue = null;

		try {

			// io.File to bytes
			RandomAccessFile f = new RandomAccessFile(FILE_NAME, "r");
			byte[] bytes = new byte[(int) f.length()];
			f.read(bytes);

			ByteArrayInputStream bs = new ByteArrayInputStream(bytes);
			if (bs.available() == 0) {
				f.close();
				return null;
			}
			ObjectInputStream ois = new ObjectInputStream(bs);
			theQueue = ois.readObject();
			ois.close();
			f.close();
		} catch (Exception e) {
			throw new PersistenceException(e);
		}

		return (List<Object>) theQueue;
	}

}
